package com.demo.modules.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.common.annotation.SysLog;
import com.demo.common.constant.Constant;
import com.demo.common.base.controller.BaseController;
import com.demo.common.exception.RRException;
import com.demo.common.utils.PageUtils;
import com.demo.common.base.R;
import com.demo.modules.sys.entity.SysMenuEntity;
import com.demo.modules.sys.form.SysMenuQueryForm;
import com.demo.modules.sys.service.ShiroService;
import com.demo.modules.sys.service.SysMenuService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 系统菜单
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private ShiroService shiroService;

    /**
     * 导航菜单 和 配置
     */
    @GetMapping("/nav")
    public R nav() {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
        Set<String> permissions = shiroService.getUserPermissions(getUserId());
        return R.ok().put("menuList", menuList).put("permissions", permissions);
    }

    /**
     * 查询分页数据
     */
    @GetMapping("/page")
    public R<PageUtils<SysMenuEntity>> page(SysMenuQueryForm params) {
        PageUtils<SysMenuEntity> page = sysMenuService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 所有菜单列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:menu:list")
    public R<List<SysMenuEntity>> list(SysMenuQueryForm params) {
        LambdaQueryWrapper<SysMenuEntity> query = new LambdaQueryWrapper<>();
        query.orderByAsc(SysMenuEntity::getOrderNum);
        List<SysMenuEntity> menuList = sysMenuService.list(new LambdaQueryWrapper<SysMenuEntity>()
                .inSql(getUserId() != Constant.SUPER_ADMIN, SysMenuEntity::getId, StrUtil.format("select rm.menu_id from sys_role_menu rm join sys_user_role ur on rm.role_id = ur.role_id where ur.user_id={}", getUserId()))
                .orderByAsc(SysMenuEntity::getParentId)
                .orderByAsc(SysMenuEntity::getOrderNum)
        );

        return R.ok(menuList);
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @GetMapping("/select")
    public R<List<SysMenuEntity>> select(SysMenuQueryForm params) {
        //查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.list(new LambdaQueryWrapper<SysMenuEntity>()
                .ne(SysMenuEntity::getType, 2)
                .orderByAsc(SysMenuEntity::getOrderNum)
        );

        return R.ok(menuList);
    }

    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    public R<SysMenuEntity> info(@PathVariable("menuId") Long menuId) {
        SysMenuEntity menu = sysMenuService.getById(menuId);
        return R.ok(menu);
    }

    /**
     * 保存
     */
    @SysLog("保存菜单")
    @PostMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public R save(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);
        sysMenuService.save(menu);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改菜单")
    @PostMapping("/update")
    @RequiresPermissions("sys:menu:update")
    public R update(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);
        sysMenuService.updateById(menu);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除菜单")
    @PostMapping("/delete/{menuId}")
    @RequiresPermissions("sys:menu:delete")
    public R delete(@PathVariable("menuId") long menuId) {
        if (menuId <= 31) {
            return R.error("系统菜单，不能删除");
        }
        //判断是否有子菜单或按钮
        List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
        if (menuList.size() > 0) {
            return R.error("请先删除子菜单或按钮");
        }
        sysMenuService.delete(menuId);
        return R.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            throw new RRException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            menu.setParentId(0L);
        }

        //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new RRException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new RRException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new RRException("上级菜单只能为菜单类型");
            }
        }
    }

    /**
     * 查询所有下级
     */
    @GetMapping("/queryAllChildren")
    public R<List<SysMenuEntity>> queryAllChildren(@RequestParam Long parentId) {
        return R.ok(sysMenuService.queryAllChildren(parentId));
    }
}
